﻿using FastExecutor.Base.Design;
using FastExecutor.Base.Model;
using FastExecutor.Base.Util;
using FastExecutor.ORG.DB;
using FastExecutor.ORG.Entity;
using FastExecutor.ORG.Enum;
using FastIOC.Annotation;
using FastUtil.Base;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace FastExecutor.ORG.Controller
{
    [RouteArea("Frame")]
    [RoutePrefix("Module")]
    public class ModuleController : FastTemplateController<Frame_Module>
    {
        [AutoWired]
        private DB_ModuleRight @DB_ModuleRight;
        [AutoWired]
        private DB_UserRoleRelation @DB_UserRoleRelation;

        [Route("List")]
        public ActionResult List()
        {
            return View("~/Views/Frame/Module/Module_List.cshtml");
        }
        [Route("Add")]
        public ActionResult Add()
        {
            return View("~/Views/Frame/Module/Module_Add.cshtml");
        }
        [Route("Edit")]
        public ActionResult Edit()
        {
            return View("~/Views/Frame/Module/Module_Edit.cshtml");
        }

        [HttpPost, Route("FindList")]
        public override ActionResult FindList()
        {

            JObject Params = GetParams();
            string ModuleName = Convert.ToString(Params["ModuleName"]);
            string ParentModuleCode = Convert.ToString(Params["ParentModuleCode"]);
            bool SearchInAll = Convert.ToBoolean(Params["SearchInAll"]);
            if (SearchInAll)
            {
                if (!string.IsNullOrEmpty(ModuleName))
                {
                    ListWhereText += string.Format(" and ModuleName like '%{0}%'", ModuleName);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(ModuleName))
                {
                    ListWhereText += string.Format(" and ModuleName like '%{0}%'", ModuleName);
                }
                if (!string.IsNullOrEmpty(ParentModuleCode))
                {
                    if (ParentModuleCode == "Top")
                    {
                        ListWhereText += string.Format(" and LENGTH(ModuleCode)={0}", 4);
                    }
                    else
                    {
                        ListWhereText += string.Format(" and LENGTH(ModuleCode)={0} and ModuleCode like '{1}%'", ParentModuleCode.Length + 4, ParentModuleCode);
                    }

                }
            }

            return base.FindList();
        }

        [HttpPost, Route("FindDetail")]
        public override ActionResult FindDetail()
        {
            return base.FindDetail();
        }

        [HttpPost, Route("OperateAdd")]
        public override ActionResult OperateAdd(Frame_Module Entity)
        {
            return base.OperateAdd(Entity);
        }

        [HttpPost, Route("OperateUpdate")]
        public override ActionResult OperateUpdate()
        {
            return base.OperateUpdate();
        }

        [HttpPost, Route("OperateBatchDelete")]
        public override ActionResult OperateBatchDelete()
        {
            ReturnValue result = new ReturnValue();
            JObject Params = GetParams();
            bool IsAuth = true;
            string keyguidlist = Convert.ToString(Params["KeyGuidList"]);
            string[] keyguidarray = keyguidlist.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string keyguid in keyguidarray)
            {
                List<Frame_Module> subou = DB_Fast.FindAll(string.Format(" and ParentModuleGuid='{0}'", keyguid));
                if (subou.Count > 0)
                {
                    IsAuth = false;
                    result.Add("code", -100);
                    result.Add("msg", "选择的菜单有下级菜单，无法删除！");
                    break;
                }

            }
            if (IsAuth)
            {
                DB_Fast.BatchDelete(keyguidarray.ToList());
            }
            return result;
        }


        [Route("Tree")]
        public ActionResult Tree()
        {
            ReturnValue result = new ReturnValue();
            List<Frame_Module> AllModuleList = DB_Fast.FindAll("", "OrderNum desc");
            List<Tree> AllTreeList = new List<Tree>();
            foreach (Frame_Module item in AllModuleList)
            {
                Tree treenode = new Tree();
                treenode.id = item.RowGuid;
                treenode.label = item.ModuleName;
                treenode.paerntGuid = item.ParentModuleGuid;
                treenode.AddAtttibute("modulecode", item.ModuleCode);
                AllTreeList.Add(treenode);
            }
            List<Tree> TreeNodeList = TreeBuilder.Build("Top", AllTreeList);
            result.Add("tree", TreeNodeList);
            return result;
        }

        [Route("GetMainPageMenu")]
        public ActionResult GetMainPageMenu()
        {
            ReturnValue result = new ReturnValue();
            JObject Params = GetParams();
            List<Tree> TreeNodeList = null;
            List<Frame_Module> AllModuleList = DB_Fast.FindAll("", "OrderNum desc").Where(a => a.IsEnable == 10).ToList();
            //权限
            List<Frame_ModuleRight> RightList = @DB_ModuleRight.FindAll();
            List<Frame_UserRolerelation> UserRoleRelation = @DB_UserRoleRelation.FindAll(string.Format(" and UserGuid='{0}'", UserGuid));
            List<string> RoleGuidList = new List<string>();
            foreach (Frame_UserRolerelation item in UserRoleRelation)
            {
                RoleGuidList.Add(item.RoleGuid);
            }
            //获取当前登陆用户拥有的菜单权限
            List<Frame_ModuleRight> RightFilterList = RightList.Where(a =>
                (a.RightGuid == OUGuid && a.RightType == (int)FrameEnum.ModuleRightType.OU) ||
                (a.RightGuid == UserGuid && a.RightType == (int)FrameEnum.ModuleRightType.User) ||
                (RoleGuidList.Contains(a.RightGuid) && a.RightType == (int)FrameEnum.ModuleRightType.Role)).ToList();
            List<string> ModuleuidList = new List<string>();
            foreach (Frame_ModuleRight item in RightFilterList)
            {
                ModuleuidList.Add(item.ModuleGuid);
            }
            List<Frame_Module> AllModuleCopyList = CopyUtil.CopyList<Frame_Module>(AllModuleList).Where(a => ModuleuidList.Contains(a.RowGuid)).ToList();
            //对于子菜单有权限而父级菜单未赋值权限的，需要自动补齐
            for (int i = 0; i < AllModuleCopyList.Count; i++)
            {
                Frame_Module Module = AllModuleCopyList[i];
                if (Module.ParentModuleGuid != "Top")
                {
                    //如果不是顶级菜单就要验证本菜单的父级菜单是否在菜单列表中
                    List<Frame_Module> AllModuleCopyListCopy = AllModuleCopyList.Where(a => a.RowGuid == Module.ParentModuleGuid).ToList();
                    if (AllModuleCopyListCopy.Count == 0)
                    {
                        AllModuleCopyList.Add(AllModuleList.Where(a => a.RowGuid == Module.ParentModuleGuid).ToList()[0]);
                    }
                }
            }
            AllModuleList = AllModuleCopyList.OrderByDescending(a => a.OrderNum).ToList();

            string Modle = Convert.ToString(Params.GetValue("Modle"));
            if (Modle == "Top")
            {
                AllModuleList = AllModuleList.Where(a => a.ModuleCode.Length == 4).ToList();
                List<Tree> AllTreeList = new List<Tree>();
                foreach (Frame_Module item in AllModuleList)
                {
                    Tree treenode = new Tree();
                    treenode.id = item.RowGuid;
                    treenode.label = item.ModuleName;
                    treenode.paerntGuid = item.ParentModuleGuid;
                    treenode.AddAtttibute("modulecode", item.ModuleCode);
                    treenode.AddAtttibute("moduleurl", item.ModuleUrl);
                    AllTreeList.Add(treenode);
                }
                TreeNodeList = TreeBuilder.Build("Top", AllTreeList);
            }
            else if (Modle == "Left")
            {
                string ParentModuleGuid = Convert.ToString(Params.GetValue("ParentModuleGuid"));
                List<Tree> AllTreeList = new List<Tree>();
                foreach (Frame_Module item in AllModuleList)
                {
                    Tree treenode = new Tree();
                    treenode.id = item.RowGuid;
                    treenode.label = item.ModuleName;
                    treenode.paerntGuid = item.ParentModuleGuid;
                    treenode.AddAtttibute("modulecode", item.ModuleCode);
                    treenode.AddAtttibute("moduleurl", item.ModuleUrl);
                    AllTreeList.Add(treenode);
                }
                TreeNodeList = TreeBuilder.Build(ParentModuleGuid, AllTreeList);
            }
            result.Add("tree", TreeNodeList);
            return result;
        }
    }
}
